package com.soboot.security.converter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.soboot.base.constant.BaseConstant;
import com.soboot.base.model.BaseRole;
import com.soboot.base.model.BaseUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:
 * @createTime: 2022年09月20日 12:48:52
 * @version:
 * @Description:
 * @Copyright:
 */
public class BaseUserAuthenticationConverter implements UserAuthenticationConverter {

    private static final String N_A = "N/A";

    private Collection<? extends GrantedAuthority> defaultAuthorities;

    public void setDefaultAuthorities(String[] defaultAuthorities) {
        this.defaultAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.arrayToCommaDelimitedString(defaultAuthorities));
    }

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap();
        response.put(USERNAME, authentication.getName());
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
        return response;
    }

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(USERNAME)) {
            Object principal = map.get(USERNAME);
            Collection<? extends GrantedAuthority> authorities = this.getAuthorities(map);

            String id = String.valueOf(map.get(BaseConstant.UserAdditionalInfo.USERID.getKey()));
            String username = (String) map.get(BaseConstant.UserAdditionalInfo.USERNAME.getKey());
            String nickname = (String) map.get(BaseConstant.UserAdditionalInfo.NICKNAME.getKey());

            String dept = (String) map.get(BaseConstant.UserAdditionalInfo.DEPT.getKey());
            List<BaseRole> roles = (List<BaseRole>) map.get(BaseConstant.UserAdditionalInfo.ROLE.getKey());
            List<String> posts = (List<String>) map.get(BaseConstant.UserAdditionalInfo.POST.getKey());

            BaseUser user = new BaseUser(Integer.valueOf(id), nickname, username, N_A, true
                    , true, true, true, authorities);
            if (StrUtil.isNotBlank(dept)){
                user.setDeptName(dept);
            }
            if (CollUtil.isNotEmpty(roles)){
                user.setRoles(roles);
            }
            if (CollUtil.isNotEmpty(posts)){
                user.setPosts(posts);
            }
            return new UsernamePasswordAuthenticationToken(user, N_A, authorities);
        }
        return null;
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        if (!map.containsKey(AUTHORITIES)) {
            return this.defaultAuthorities;
        } else {
            Object authorities = map.get(AUTHORITIES);
            if (authorities instanceof String) {
                return AuthorityUtils.commaSeparatedStringToAuthorityList((String)authorities);
            } else if (authorities instanceof Collection) {
                return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.collectionToCommaDelimitedString((Collection)authorities));
            } else {
                throw new IllegalArgumentException("Authorities must be either a String or a Collection");
            }
        }
    }
}
